package org.university.service.impl;

import jakarta.persistence.criteria.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.university.entity.Teacher;
import org.university.enums.GlobalEnums;
import org.university.repository.TeacherRepository;
import org.university.service.TeacherService;

import javax.validation.ValidationException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TeacherServiceImpl extends GenericServiceImpl<Teacher, String> implements TeacherService {

    private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);
    private final TeacherRepository teacherRepository;

    public TeacherServiceImpl(TeacherRepository repository, TeacherRepository teacherRepository) {
        super(repository);
        this.teacherRepository = teacherRepository;
    }

    @Override
    public Teacher save(Teacher teacher) {
        logger.info("保存教师ID: {}", teacher.getTeacherId());
        if (teacher.getTeacherId() != null && teacherRepository.existsById(teacher.getTeacherId())) {
            throw new IllegalArgumentException("教师ID已存在: " + teacher.getTeacherId());
        }
        return teacherRepository.save(teacher);
    }

    @Override
    public Page<Teacher> findAll(Pageable pageable) {
        logger.info("查询所有教师: 分页信息={}", pageable);
        return teacherRepository.findByDeletedFalse(pageable);
    }

    @Override
    public Page<Teacher> findAll() {
        logger.info("查询所有教师（无分页）");
        return teacherRepository.findByDeletedFalse(Pageable.unpaged());
    }

    @Override
    public void deleteById(String id) {
        logger.info("删除教师ID: {}", id);
        teacherRepository.findById(id).ifPresent(teacher -> {
            teacher.setDeleted(1);
            teacherRepository.save(teacher);
        });
    }

    @Override
    public Page<Teacher> searchTeachers(String teacherId, String teacherName, String gender,
                                        String birthDate, String hireDate, String deptId,
                                        String title, String phone, String email, Pageable pageable) {
        logger.info("多条件查询教师: 分页信息={}", pageable);
        return teacherRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("deleted"), 0));

            if (StringUtils.hasText(teacherId)) {
                predicates.add(cb.like(cb.lower(root.get("teacherId")),
                        "%" + teacherId.toLowerCase() + "%"));
            }

            if (StringUtils.hasText(teacherName)) {
                predicates.add(cb.like(cb.lower(root.get("teacherName")),
                        "%" + teacherName.toLowerCase() + "%"));
            }

            if (StringUtils.hasText(gender)) {
                try {
                    GlobalEnums.Gender.valueOf(gender);
                    predicates.add(cb.equal(root.get("gender"), GlobalEnums.Gender.valueOf(gender)));
                } catch (IllegalArgumentException e) {
                    throw new ValidationException("无效的性别值，应为 '男' 或 '女'");
                }
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            if (StringUtils.hasText(birthDate)) {
                try {
                    LocalDate date = LocalDate.parse(birthDate, formatter);
                    predicates.add(cb.equal(root.get("birthDate"), date));
                } catch (DateTimeParseException e) {
                    throw new ValidationException("无效的出生日期格式，应为 yyyy-MM-dd");
                }
            }

            if (StringUtils.hasText(hireDate)) {
                try {
                    LocalDate date = LocalDate.parse(hireDate, formatter);
                    predicates.add(cb.equal(root.get("hireDate"), date));
                } catch (DateTimeParseException e) {
                    throw new ValidationException("无效的入学日期格式，应为 yyyy-MM-dd");
                }
            }

            if (StringUtils.hasText(deptId)) {
                try {
                    predicates.add(cb.equal(root.get("deptId"), Integer.parseInt(deptId)));
                } catch (NumberFormatException e) {
                    throw new ValidationException("无效的学院ID，应为整数");
                }
            }

            if (StringUtils.hasText(title)) {
                try {
                    predicates.add(cb.equal(root.get("title"), Integer.parseInt(title)));
                } catch (NumberFormatException e) {
                    throw new ValidationException("无效的职称，请检查输入");
                }
            }

            if (StringUtils.hasText(phone)) {
                predicates.add(cb.like(root.get("phone"), "%" + phone + "%"));
            }
            if (StringUtils.hasText(email)) {
                predicates.add(cb.like(root.get("email"), "%" + email + "%"));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        }, pageable);
    }
}